from Products.Five import BrowserView
from Products.CMFCore.utils import getToolByName
from Products.ATVocabularyManager import NamedVocabulary
import datetime
import time
import inspect
import calendar

log = __import__("logging").getLogger("apkn.repository.browser")

class Html(BrowserView):

    def format_date(self, date_string):
        """
        Format the date i.e. from '1982/09/15 00:00:00 GMT+3' to '15-Sep-1982'
        """
        if len( str(date_string) ) == 0:
            new_day = None
        else:
            the_day, the_time, the_tzone = str(date_string).split(" ")
            day_obj = time.strptime(the_day, "%Y/%m/%d")
            new_day = time.strftime("%d-%b-%Y", day_obj)
        
        return new_day
        
        
    def get_years(self): 
        """
        Get a list of years and return
        """
    
        items = []

        # Get a datetime object
        now = datetime.datetime.now()
        currentYear = now.year
        startYear = 1970
        
        for eachYear in range(startYear, (currentYear + 5), 1):
            items.append( str(eachYear) ) 

        return items
        
    def get_month_name(self, month_index):
        """
        Get the month name from the month index e.g. Given a month index of 3,
        we should return March, since it is the third month.
        """
        
        name_of_month = ""
        
        try:
        
            if (month_index is not None) or (month_index is not ""):
                name_of_month = calendar.month_name[int(month_index)]
            else:
                name_of_month = None
        except TypeError:
            print("Argument must be a string or a number, not a Missing.Value")
        
        return name_of_month
        
        
    def get_parliamentary_types(self):
        """
        Fetch the Legislative Types from the vocabulary and return them 
        back as a list
        """
    
        legislative_types = []        
        legislative_vocab = NamedVocabulary('org.apkn.metadata.vocabularies.parliamentarytypes')
        legislative_terms = legislative_vocab.getDisplayList(self).items()
        
        for term in legislative_terms:
            legislative_types.append( (term[0], term[1]) )
        
        return legislative_types
        
        
    def get_groups(self): 
        """
        Get groups within the application and return as a list.
        """

        items = []
        
        gtool = getToolByName(self, 'portal_groups')
        for group in gtool.listGroups():
            items.append((group.getId(), group.title_or_id()))

        return items
        
        
    def queryItemRepository(self):
        """
        Perform a search returning repository items matching the criteria
        """
        
        query = {}
        
        portal_catalog = getToolByName(self, 'portal_catalog')
        
        query['portal_type'] = "RepositoryItem" #['RepositoryItem', 'RepositoryCollection']
        query['path'] = {'query' : '/'.join(self.context.getPhysicalPath()), 'depth' : 1 }
        query['sort_on'] = "sortable_title"
        query['sort_order'] = "ascending"
      
        for key, value in self.request.form.iteritems():
            if value is not '' and key != 'Search':
               query[key] = value
        
        return portal_catalog.searchResults(query)
        
        
    def get_form_data(self):
        """
        Get the form submitted data and return it back to re-populate the form.
        """
        return {
            "SearchableText": self.request.form.get("SearchableText", ""),
            "item_publication_year": self.request.form.get("item_publication_year", ""),
            "legislative_type": self.request.form.get("legislative_type", ""),
        }
